package ligapes.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ligapes.model.bean.Usuario;
import ligapes.model.dao.UsuarioDAO;

public class AcessoController extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		String logout = req.getParameter("LOGOUT");
		if (logout != null && logout.equals("Y")) {
			HttpSession session = req.getSession(true);
			session.invalidate();
		}
		resp.sendRedirect("restrito/index.jsp?PAGE=P");
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		
		UsuarioDAO usuarioDAO = new UsuarioDAO();
		Usuario usuario = usuarioDAO.carregaPorLoginESenha(username, password);
		
		if (usuario != null) {
			HttpSession session = req.getSession(true);
			session.setAttribute("usuario", usuario);
			
			RequestDispatcher rd = req.getRequestDispatcher("/restrito/index.jsp?PAGE=P");
			rd.forward(req, resp);
		} else {
			resp.sendRedirect("publico/index.jsp");
		}
	}
}
